<template>
  <view class="page">
    <view v-if="$data.info">
      <!-- 轮播图 -->
      <view v-if="$data.imgList.length">
        <up-swiper
          :list="$data.imgList"
          height="50vh"
          :radius="0"
          imgMode="scaleToFill"
          @click="onCheckImg"
        ></up-swiper>
      </view>
      <!-- 基本信息 -->
      <view class="basic">
        <view class="basic_collect" @tap="onCollect">
          <image
            :src="
              $data.info.collectStatus == collectStatus.not
                ? ImgIconCollectGray
                : ImgIconCollectGreen
            "
          />
          <view
            class="text-center text-nowarp"
            :style="[$data.info._collectConfig.textStyle]"
          >
            {{ $data.info._collectConfig.typeName }}
          </view>
        </view>
        <view class="basic_price">
          <text class="text-price">{{ $data.info.showPrice }}</text>
          <text>起</text>
        </view>
        <view class="basic_name">{{ $data.info.title }}</view>
        <view class="basic_desc">{{ $data.info.intro }}</view>
        <view class="basic_tag" v-if="$data.info.serviceTagIds">
          <view
            class="basic_tag_item"
            v-for="(item, index) of $data.info.serviceTagNameArr"
            :key="index"
          >
            <image :src="ImgCheckGreen" />
            <text class="margin-left-xs">{{ item }}</text>
          </view>
        </view>
        <!-- <view class="basic_coupon" v-if="$data.info._coupon">
          <view class="basic_coupon_left">
            <text class="label text-nowarp">单次优惠</text>
            <view class="coupon_box" @tap="() => ($data.couponShow = true)">
              <view class="round_top"></view>
              <view class="coupon_box_left">
                <view class="u-line-1">{{ $data.info._coupon.title }}</view>
              </view>
              <view class="coupon_box_right">领</view>
              <view class="round_bottom"></view>
            </view>
          </view>
          <view class="basic_coupon_right">
            <image :src="ImgIconRightGray" />
          </view>
        </view> -->
      </view>
      <!-- 详情 -->
      <!-- <view class="content">
        <view class="comment">
          <ListServiceComment ref="RefData" />
        </view>
        <up-parse v-if="$data.content" :content="$data.content"></up-parse>
      </view> -->
      <!-- 底部购买 -->
      <view class="foot foot_buy">
        <view class="foot_buy_left" @tap="() => ($data.csphoneShow = true)">
          <image :src="ImgIconKefuGray" />
          <view class="text-center text-nowarp">客服电话</view>
        </view>
        <!-- <button
          open-type="im"
          data-im-id="5408828"
          @im="im"
          class="btn u-reset-button"
        >
          客服
        </button> -->
        <view class="foot_buy_right" @tap="onBeforBuy"> 立即购买 </view>
      </view>
      <PopupTakeCoupon
        v-model:show="$data.couponShow"
        :list="$data.couponList"
        @take="onTake"
      />
      <PopupCSPhone v-model:show="$data.csphoneShow" title="官方客服电话" />
      <PopupSku
        v-model:show="$data.skuShow"
        :domesticServiceId="searchObj.domesticServiceId"
        :tips="$data.info.tips"
        :tikTokSkuId="$data.skuId"
        @choose="onChooseSku"
      />
    </view>
    <view v-else>
      <wakin-data-empty :message="$data.message">
        <view class="back-btn common_btn" @tap="onBack">返回首页</view>
      </wakin-data-empty>
    </view>
    <!-- 详情 -->
    <view v-show="$data.info" class="content">
      <!-- 评论 -->
      <view class="comment">
        <view class="comment_top">
          <view class="comment_top--left">评价({{ $data.commentTotal }})</view>
          <view class="comment_top--right" @tap="onToComment">
            <text>好评率{{ $data.commentGood }}%</text>
            <view class="margin-left-xs">
              <up-icon
                name="arrow-right"
                :color="BasicConfig.MainColor"
              ></up-icon>
            </view>
          </view>
        </view>
        <ListServiceComment ref="RefData" @total="onCommentTotal" />
      </view>
      <!-- 详情 -->
      <!-- <view v-show="$data.content" class="padding-"> -->
      <view class="text-center text-bold text-xl margin-tb">详情</view>
      <up-parse
        :content="$data.content"
        :loadingImg="ImgParseLoadingColor"
      ></up-parse>
      <!-- </view> -->
    </view>
    <popupLogin />
    <!-- <PopupReason v-model:show="$data.reasonShow" /> -->
  </view>
</template>

<script setup>
// import PopupReason from "./order/components/PopupReason.vue";
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import {
  onLoad,
  onShow,
  onHide,
  onReady,
  onPageScroll,
  onReachBottom,
  onPullDownRefresh,
  onShareAppMessage,
  onShareTimeline,
} from "@dcloudio/uni-app";
import BasicConfig from "@/utils/config";
import { getServiceDetail } from "../../api/Interface/service";
import {
  useGetLocationStorage,
  useGetUserStorage,
  useSetServiceShareStorage,
  useSetLocationStorage,
} from "../../hooks/useStorage";
import errorCode from "../../utils/http/errorCode";
import {
  ImgCheckGreen,
  ImgIconCollectGray,
  ImgIconCollectGreen,
  ImgIconKefuGray,
  ImgIconRightGray,
  ImgParseLoadingColor,
} from "../../utils/iconMap";
import PopupTakeCoupon from "../components/PopupTakeCoupon.vue";
import { takeCoupnStatus, takeCoupnStatusConfig } from "../../enums/coupon";
import { couponCollection, getCoupon } from "../../api/Interface/coupons";
import { collectStatus, collectStatusConfig } from "../../enums/common";
import PopupCSPhone from "../../components/PopupCSPhone.vue";
import ListServiceComment from "../components/ListServiceComment.vue";
import PopupSku from "../components/PopupSku.vue";
import { eventBus } from "../../enums/eventBus";
import { jumpPage } from "../../utils/route/route";
import { useImgSrc } from "../../hooks/useImg";
import qs from "qs";
import {
  useGetFuzzyAddress,
  useGetLocationAddress,
} from "../../hooks/useLocation";
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  imgList: [],
  info: null,
  couponShow: false, // 领券弹窗
  couponList: [],
  csphoneShow: false, // 客服电话弹窗 cs : csutom service 缩写
  commentTotal: 0,
  commentGood: 0,
  skuShow: false, // 点击立即购买,弹出sku选择弹窗
  userInfo: {},
  skuId: "", // 抖音直播传过来的选择的skuId
  message: "数据加载中...",
  LocationStorage: null, // 用户缓存的地市信息
  reasonShow: true,
});
const searchObj = reactive({
  domesticServiceId: "",
  is_picture: 0,
  page: 1,
  limit: 2,
});
/** 初始化数据 */
const __init = async () => {
  $data.message = "数据加载中...";
  let location = useGetLocationStorage();
  if (!location) {
    try {
      await useGetLocationAddress();
    } catch (error) {}
  }
  location = useGetLocationStorage();
  // console.log("useGetLocationStorage", location, code);
  await getServiceDetail({
    cityCode: location.code,
    domesticServiceId: searchObj.domesticServiceId,
  })
    .then((res) => {
      if (res.code === errorCode.success) {
        const { picArr, videoUrl, content } = res.data;
        $data.content = content;
        $data.imgList = [videoUrl, ...picArr]
          .filter((item) => !!item)
          .map((m) => (m = useImgSrc(m)));
        $data.info = res.data;
        $data.info._coupon = null;
        formatCollect();
        if ($data.info.couponArr && $data.info.couponArr.length > 0) {
          $data.info._coupon = $data.info.couponArr[0];
          $data.couponList = $data.info.couponArr;
          $data.couponList.forEach((item) => {
            item._config = takeCoupnStatusConfig[item.takeStatus] ?? {
              value: takeCoupnStatus.untake,
              typeName: "未领取",
              btnStyle: {
                color: "#ffffff",
                background: BasicConfig.MainColor,
              },
            };
          });
        }
      } else {
        // BasicConfig.toast(res.msg);
        $data.message = "暂未覆盖您所在区域，服务版图加速拓展中！";
        // setTimeout(() => {
        //   uni.navigateBack({
        //     delta: 1,
        //   });
        // }, 1500);
      }
    })
    .catch((err) => {
      $data.message = "暂未覆盖您所在区域，服务版图加速拓展中！";
    });
};
const onCommentTotal = (e, p) => {
  $data.commentTotal = e;
  $data.commentGood = p;
  console.log("onCommentTotal", e, p);
};
/** 收藏/取消收藏 */
const onCollect = () => {
  const { collectStatus: _collectStatus } = $data.info;
  const status = _collectStatus == collectStatus.not ? 1 : 2;
  couponCollection({
    domesticServiceId: $data.info.domesticServiceId,
    status,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info.collectStatus =
        _collectStatus == collectStatus.not
          ? collectStatus.done
          : collectStatus.not;
      formatCollect();
    }
  });
};
/** 收藏/取消收藏状态变更 */
const formatCollect = () => {
  if (!$data.info) return;
  const config = collectStatusConfig[$data.info.collectStatus];
  $data.info._collectConfig = config ?? {
    value: collectStatus.not,
    typeName: "收藏",
    textStyle: {
      color: "#bbbbbb",
    },
  };
};
/** 领取优惠券 */
const onTake = (e, i) => {
  getCoupon({ couponId: e.couponId }).then((res) => {
    BasicConfig.toast(res.msg);
    if (res.code === errorCode.success) {
      $data.couponList[i].takeStatus = res.data.takeStatus;
      $data.couponList[i]._config =
        takeCoupnStatusConfig[$data.couponList[i].takeStatus];
    }
  });
};
const onBeforBuy = () => {
  $data.skuShow = true;
};
/** 选择sku回调 */
const onChooseSku = (id, skus) => {
  console.log("skus", skus);
  setTimeout(() => {
    uni.$emit(eventBus.service.confirm, skus);
  }, 1000);
  jumpPage({
    to: "/package-service/pages/order/confirm",
    query: {
      id: id,
    },
  });
};
const onCheckImg = () => {};
/** 跳转评论页 */
const onToComment = () => {
  jumpPage({
    to: "/package-service/pages/comment",
    query: {
      domesticServiceId: searchObj.domesticServiceId,
    },
  });
};
const contact = (e) => {
  console.log("contact", e);
};
const im = (e) => {
  console.log("im", e);
};
const onBack = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};
const RefData = ref();
/** 获取数据列表 */
const fnGetDatas = (type = $vm.$ListLoadEnum.load) => {
  RefData.value.loadDatas(type, searchObj);
};
/** 初始化数据 */
const init = async () => {
  $data.message = "数据加载中...";
  await getServiceDetail({
    cityCode: $data.LocationStorage.code,
    domesticServiceId: searchObj.domesticServiceId,
  })
    .then((res) => {
      if (res.code === errorCode.success) {
        const { picArr, videoUrl, content } = res.data;
        $data.content = content;
        $data.imgList = [videoUrl, ...picArr]
          .filter((item) => !!item)
          .map((m) => (m = useImgSrc(m)));
        $data.info = res.data;
        $data.info._coupon = null;
        formatCollect();
        if ($data.info.couponArr && $data.info.couponArr.length > 0) {
          $data.info._coupon = $data.info.couponArr[0];
          $data.couponList = $data.info.couponArr;
          $data.couponList.forEach((item) => {
            item._config = takeCoupnStatusConfig[item.takeStatus] ?? {
              value: takeCoupnStatus.untake,
              typeName: "未领取",
              btnStyle: {
                color: "#ffffff",
                background: BasicConfig.MainColor,
              },
            };
          });
        }
      } else {
        $data.message = "暂未覆盖您所在区域，服务版图加速拓展中！";
      }
    })
    .catch((err) => {
      $data.message = "暂未覆盖您所在区域，服务版图加速拓展中！";
    });
};
const initLocation = async () => {
  $data.LocationStorage = useGetLocationStorage() || {
    name: "重新定位",
    code: null,
  };
  if (!$data.LocationStorage?.code) {
    try {
      uni.showModal({
        content: "小程序申请获取您的地理位置信息用以为您推送最近的服务",
        confirmColor: BasicConfig.MainColor,
        confirmText: "授权",
        success: async (success) => {
          if (success.confirm) {
            await useGetLocationAddress();
          } else {
            useSetLocationStorage({
              code: "2301",
              name: "哈尔滨市",
            });
          }
          $data.LocationStorage = useGetLocationStorage();
          $data.cityName = $data.LocationStorage?.name;
          setTimeout(async () => {
            await init();
          }, 100);
        },
      });
    } catch (error) {}
  } else {
    $data.LocationStorage = useGetLocationStorage();
    $data.cityName = $data.LocationStorage?.name;
    await init();
  }
};
onLoad((options) => {
  console.log("H5带入参数", options);
  let paramList = [];
  if (options.scene) {
    console.log("e.scene", options.scene);
    const obj = qs.parse(options.scene); // {q=1,1,1,57,1,50:""}
    console.log("e.scene obj", options.obj);
    paramList = Object.keys(obj)[0].split("=")[1].split(",");
  } else if (options && options.q) {
    console.log("e.q", options.q);
    paramList = options.q.split(",");
  }
  if (paramList && paramList.length > 0) {
    searchObj.domesticServiceId = paramList[0];
  }
  $data.userInfo = useGetUserStorage();
  console.log("userInfo", $data.userInfo);
  // 推荐官分享进入
  if (options.share_domesticServiceId) {
    const domesticServiceId = options.share_domesticServiceId;
    const userId = options.share_userId;
    searchObj.domesticServiceId = domesticServiceId;
    useSetServiceShareStorage({ domesticServiceId, userId });
  } else {
    searchObj.domesticServiceId = options.id;
    $data.skuId = options.skuId;
    if (options.skuId) $data.skuShow = true;
  }
  console.log("服务详情 options", options);
  // init();
  initLocation();
});
onReady(() => {
  setTimeout(() => {
    fnGetDatas($vm.$ListLoadEnum.load);
  }, 1000);
});
onShareAppMessage(() => {
  return {
    // path: `/pages/index/index?shareUserId=${userInfo.userId}`,
    path: `/package-service/pages/index?share_domesticServiceId=${
      searchObj.domesticServiceId
    }&share_userId=${$data.userInfo?.userId ?? ""}`,
  };
});
onShareTimeline(() => {
  return {
    path: `/package-service/pages/index?share_domesticServiceId=${
      searchObj.domesticServiceId
    }&share_userId=${$data.userInfo?.userId ?? ""}`,
    query: `share_domesticServiceId=${params.domesticServiceId}&share_userId=${
      $data.userInfo?.userId ?? ""
    }`,
  };
});
</script>

<style lang="scss" scoped>
.page {
  background: #f7f8fa;
  width: 100vw;
  min-height: 100vh;
  padding-bottom: 200rpx;
  .basic {
    padding: 30rpx;
    position: relative;
    background: #ffffff;
    &_collect {
      position: absolute;
      width: 100rpx;
      height: 100rpx;
      top: 30rpx;
      right: 30rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      image {
        width: 50%;
        height: 50%;
      }
    }
    &_price {
      color: $main-color;
      text {
        &:first-child {
          font-size: 44rpx;
        }
        &:nth-of-type(2) {
          margin-left: 6rpx;
          font-size: 30rpx;
        }
      }
    }
    &_name {
      color: #111111;
      font-size: 38rpx;
      margin: 30rpx 0;
    }
    &_desc {
      color: #666666;
      font-size: 34rpx;
    }
    &_tag {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin: 40rpx 0;
      &_item {
        display: flex;
        align-items: center;
        color: $main-color;
        margin-right: 30rpx;
        margin-bottom: 20rpx;
        image {
          width: 30rpx;
          height: 30rpx;
          border-radius: 100%;
        }
        text {
          // margin-bottom: 6rpx;
          font-size: 30rpx;
        }
      }
    }
    &_coupon {
      background: #f7f8fa;
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
      &_left {
        display: flex;
        align-items: center;
        .label {
          font-size: 30rpx;
          // font-weight: 700;
        }
        .coupon_box {
          padding: 10rpx 0;
          background: $main-color;
          color: #ffffff;
          font-size: 32rpx;
          border-radius: 15rpx;
          position: relative;
          display: flex;
          align-items: center;
          margin-left: 30rpx;
          &_left {
            width: calc(100% - 80rpx);
            text-align: center;
            padding: 0 20rpx;
            view {
              max-width: 260rpx;
            }
          }
          &_right {
            width: 80rpx;
            border-left: 1px dashed #ffffff;
            text-align: center;
          }
          $roundWidth: 20rpx;
          $roundHeight: 12rpx;
          $roundRight: 70rpx;
          .round_top {
            width: $roundWidth;
            height: $roundHeight;
            position: absolute;
            background: #ffffff;
            right: $roundRight;
            top: 0;
            border-radius: 0 0 100rpx 100rpx;
          }
          .round_bottom {
            width: $roundWidth;
            height: $roundHeight;
            position: absolute;
            background: #ffffff;
            right: $roundRight;
            bottom: 0;
            border-radius: 100rpx 100rpx 0 0;
          }
        }
      }
      &_right {
        width: 14rpx;
        height: 24rpx;
        display: flex;
        align-items: center;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .content {
    margin-top: 30rpx;
    background: #ffffff;
    .comment {
      &_top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx;
        &--left {
          font-size: 34rpx;
        }
        &--right {
          display: flex;
          align-items: center;
          color: $main-color;
          font-size: 34rpx;
        }
      }
    }
  }

  $footLeftWidth: 100rpx;
  .foot_buy {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background: #ffffff;
    &_left {
      width: $footLeftWidth;
      height: $footLeftWidth;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      image {
        width: 60%;
        height: 60%;
      }
      view {
        font-size: 26rpx;
      }
    }
    &_right {
      width: calc(100% - $footLeftWidth);
      background: $main-color;
      margin-left: 30rpx;
      color: #ffffff;
      text-align: center;
      padding: 30rpx;
      border-radius: 100rpx;
      z-index: 999;
      font-size: 34rpx;
    }
  }
  .back-btn {
    margin: auto;
    margin-top: 60rpx;
    padding: 20rpx;
  }
}
</style>
